Skip to main content

Number of 1 Bits

位运算题,做完看到题解里还有Ologk的解法,就是二分。但是在这个题目的 32 位限定下以位数计算时间复杂度没有太大意义,如果是大整数的话二分确实很有效,如果是多次调用的话缓存更为重要。所以这个函数无论怎么写复杂度都应该是O1 & O1

impl Solution {
pub fn hammingWeight (n: u32) -> i32 {
use std::convert::TryInto;
let mut n = n;
let mut res = 0;
while n > 0 {
n &= n - 1;
res += 1;
}
res.try_into().unwrap()
}
}